package com.lry.sign;

import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.signatures.BouncyCastleDigest;
import com.itextpdf.signatures.DigestAlgorithms;
import com.itextpdf.signatures.IExternalSignatureContainer;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;

/**
 * @author Ethan
 * @version 1.0
 * @description: TODO
 * @date 2021/6/24 0024
 */
public class ExternalEmptySignatureContainer implements IExternalSignatureContainer{
        private PdfDictionary sigDic;
        private String hashAlgorithm;
        private byte[] digestHash;
        public ExternalEmptySignatureContainer(PdfName filter, PdfName subFilter,String hashAlgorithm) {
            sigDic = new PdfDictionary();
            sigDic.put(PdfName.Filter, filter);
            sigDic.put(PdfName.SubFilter, subFilter);
            this.hashAlgorithm = hashAlgorithm;
        }
        @Override
        public byte[] sign(InputStream data) throws GeneralSecurityException {
            BouncyCastleDigest digest = new BouncyCastleDigest();
            try {
                this.digestHash= DigestAlgorithms.digest(data, digest.getMessageDigest(this.hashAlgorithm));
            } catch (IOException e) {
                throw new GeneralSecurityException("ExternalEmptySignatureContainer signing exception",e);
            }
            return new byte[0];
        }


        @Override
        public void modifySigningDictionary(PdfDictionary signDic) {
            signDic.putAll(sigDic);
        }

    public byte[] getDigestHash() {
        return digestHash;
    }
}
